import pandas as pd
import json
from flask import (Blueprint, request, session)
from flaskr import Utils
from flaskr.server.SheetsServer import *

import hashlib
md5 = hashlib.md5()

bp = Blueprint('concat',__name__, url_prefix='/concat')

@bp.route('', methods = ['POST'])
def concat():
    # 获取要合并的表名数组
    sheetname_list = request.json.get('sheetNames')
    # 合并表的名字
    sheet_name = request.json.get('sheetName')
    tables = []
    sheets = get_sheets()
    sheet = get_sheet(sheet_name)

    if 'sheets' not in session.keys():
        return{
            'code': 500,
            'msg': '没有加载任何表'
        }

    # sheets = session["sheets"]
    # for name in sheetname_list:
    #     for sheet in sheets:
    #         if sheet['showName'] == name:
    #             df = Utils.jsonToDataFrame(sheet['json']) #从session中拿到需要合并的表的json数据转换成DataFrame
    #             tables.append(df) #将数据存放到tables中
    #

    for name in sheetname_list:
        df = get_dataframe(name)
        tables.append(df)

    df = pd.concat(tables) #将表合并

    if not df.index.is_unique: #如果有重复索引，那么重新合并并且不根据两表索引设置索引
        df = pd.concat(tables, ignore_index=True)
    obj = {}

    if has_pkl(sheet_name):
        setPkl(df, sheet['md5'])
        df = df.head(200)

    obj['sheetName'] = 'concat_wiken'
    obj['showName'] = sheet_name
    obj['json'] = Utils.dataFrameToJson(df) #将结果转换成Json
    obj['table'] = Utils.dataFrameToHtml(df)
    obj['columns'] = Utils.getColumns(df)
    obj['types'] = Utils.getTypes(df)
    md5_str = obj['sheetName'] + '_' + obj['showName']
    md5.update(md5_str.encode(encoding='UTF-8'))
    obj['md5'] = md5.hexdigest()

    addPkl(df, obj['md5'])

    sheets.append(obj)
    session['sheets'] = sheets
    session.modified = True
    return{
        'code': 200,
        'msg': '合并成功',
        'data': obj
    }
